package fonkin.com.wifisignapp.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.io.File;

import de.hdodenhof.circleimageview.CircleImageView;
import fonkin.com.wifisignapp.R;
import fonkin.com.wifisignapp.acticity.LoginActivity;
import fonkin.com.wifisignapp.acticity.aboutMe.AppVersionActivity;
import fonkin.com.wifisignapp.acticity.aboutMe.Message;
import fonkin.com.wifisignapp.acticity.aboutMe.Procedure;
import fonkin.com.wifisignapp.acticity.aboutMe.ResetPwd;
import fonkin.com.wifisignapp.acticity.aboutMe.UserInfor;
import fonkin.com.wifisignapp.constants.AppConstants;
import fonkin.com.wifisignapp.retrofit.BaseRetrofit;
import fonkin.com.wifisignapp.utils.ReturnVo;
import fonkin.com.wifisignapp.utils.ShowToast;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;


public class AboutMeFragment extends Fragment {
    TextView textView,user_name;
    LinearLayout message,resetPwd,share,about,schedule;
    CircleImageView headPic;
    ImageView reset_infor;
    Uri uri;
    Button loginOutBtn;
    Bitmap bitmap;
    SharedPreferences pref;
    String img_path;
    private final int IMAAGE_RESULT_CODE = 1;
    private final int OPEN_CAMERA_CODE = 2;


    public static AboutMeFragment newInstance(String text){
        AboutMeFragment aboutMeFragment=new AboutMeFragment();
        Bundle bundle=new Bundle();
        bundle.putString("text",text);
        aboutMeFragment.setArguments(bundle);
        return aboutMeFragment;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.about_me_fragment,container,false);
        textView= (TextView) view.findViewById(R.id.textView);
        textView.setText(getArguments().getString("text"));
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        pref = PreferenceManager.getDefaultSharedPreferences(getContext());

        reset_infor = (ImageView)getView().findViewById(R.id.reset_infor);
        reset_infor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), UserInfor.class);
                startActivity(intent);
            }
        });


        user_name= (TextView) getView().findViewById(R.id.user_name);//用户名
        headPic = (CircleImageView)getView().findViewById(R.id.user_headpic);//用户头像
        final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getContext());
        if (pref.contains("user_name")){
            user_name.setText(pref.getString("user_name","黄洪靖"));
        }
        if (pref.contains("user_image")){
            Picasso
                    .with(getContext())
                    .load(AppConstants.IMAGE_API + pref.getString("user_image",""))
                    .error(R.drawable.un_head_pic)
                    .fit()
                    .centerCrop()
                    .into(headPic);
        }

        headPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, OPEN_CAMERA_CODE);
            }


        });

        message= (LinearLayout)getView().findViewById(R.id.message_btn);//信息
        message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShowToast.ShowToastShort("信息",getActivity());
                Intent intent = new Intent(getActivity(), Message.class);
                startActivity(intent);
            }


        });

        schedule= (LinearLayout)getView().findViewById(R.id.schedule_btn);//流程
        schedule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShowToast.ShowToastShort("流程",getActivity());
                Intent intent = new Intent(getActivity(), Procedure.class);
                startActivity(intent);
            }

        });


        resetPwd= (LinearLayout)getView().findViewById(R.id.reset_btn);//密码修改
        resetPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ResetPwd.class);
                startActivity(intent);
            }

        });

        share= (LinearLayout)getView().findViewById(R.id.share_btn);//分享
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShowToast.ShowToastShort("分享",getActivity());

            }


        });

        about= (LinearLayout)getView().findViewById(R.id.about_btn);//关于
        about.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AppVersionActivity.class);
                startActivity(intent);
            }


        });

        loginOutBtn= (Button)getView().findViewById(R.id.loginOut_btn);//登出
        loginOutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = pref.edit();
                editor.clear();
                editor.commit();
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                getActivity().onBackPressed();//销毁自己
            }


        });
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {

            case OPEN_CAMERA_CODE:
                if (resultCode == RESULT_OK) {
                    uri = data.getData();
                    String[] proj = { MediaStore.Images.Media.DATA };
                    Cursor actualimagecursor = getContext().getContentResolver().query(uri,proj,null,null,null);
                    int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    actualimagecursor.moveToFirst();
                    img_path = actualimagecursor.getString(actual_image_column_index);
                    headPic.setImageURI(uri);
                    Log.d("本地图片的地址为：",img_path+"");
                    uploadHeadPic(img_path);
                }
                break;
        }
    }

    private void uploadHeadPic(String picTath) {
        File file = new File(picTath);
        String s = file.getName().toString();
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getContext());
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"),file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("images", file.getName(), requestFile);
        RequestBody userId = RequestBody.create(MediaType.parse("multipart/form-data"),pref.getString("user_id",""));
        if (!"".equals(picTath)){
            BaseRetrofit.GetBaseRetrofit().uploadHeadpic(part,userId).enqueue(new Callback<ReturnVo<String>>() {
                @Override
                public void onResponse(Call<ReturnVo<String>> call, Response<ReturnVo<String>> response) {
                    if (response.isSuccessful()){
                        if (response.body().getCode().equals(1)){
                            ShowToast.ShowToastLong("上传成功！！！",getContext());
                        }else{
                            ShowToast.ShowToastLong("上传失败！！！",getContext());
                        }
                    }else{
                        ShowToast.ShowToastShort(AppConstants.Fail_REQUEST,getContext());
                    }
                }
                @Override
                public void onFailure(Call<ReturnVo<String>> call, Throwable t) {
                    ShowToast.ShowToastShort(AppConstants.Fail_RESPONSE,getContext());
                }
            });
        }

    }


}
